package com.zlzxm.shoesmarket.util;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Color;
import android.os.Build;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextWatcher;
import android.text.style.RelativeSizeSpan;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.KeyCharacterMap;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.DrawableRes;
import androidx.annotation.IdRes;
import androidx.annotation.LayoutRes;

import java.lang.reflect.Method;

/**
 * Created by zlz on 2018/7/18.
 * view 相关快捷帮助
 */

public class ZViewHelp {

    private static final String TAG = "ZViewHelp";

//<editor-fold defaultState="collapsed" desc="View">



    public static   <T extends View> T findById(Activity activity ,@IdRes int id){


        return activity.findViewById(id);
    }


    public static <T extends View> T setOnClickListener(Activity activity ,@IdRes int id, View.OnClickListener listener){

        T t =  findById(activity,id);

        t.setOnClickListener(listener);

        return t;
    }

    public static   <T extends  View> T findById(View view ,@IdRes int id){


        return view.findViewById(id);
    }


    public static <T extends View> T setOnClickListener(View view , @IdRes int id, View.OnClickListener listener){

        T t =  findById(view,id);

        t.setOnClickListener(listener);

        return t;
    }


    public static   <T extends  View> T findById(Dialog view , @IdRes int id){


        return view.findViewById(id);
    }


    @SuppressWarnings("UnusedReturnValue")
    public static <T extends View> T setOnClickListener(Dialog view , @IdRes int id, View.OnClickListener listener){

        T t =  findById(view,id);

        t.setOnClickListener(listener);

        return t;
    }





    public static void changeViewSize(int width,int height,View view){

        ViewGroup.LayoutParams  lp = view.getLayoutParams();

        lp.width = width;

        lp.height = height;

        view.setLayoutParams(lp);


    }

    public static  View inflate(Context context, ViewGroup parent, @LayoutRes int resource, boolean attachToRoot){

        return LayoutInflater.from(context).inflate(resource,parent,attachToRoot);
    }


    public static View setVisibility(View view,int visible){

        view.setVisibility(visible);
        return  view;
    }


    public static View setVisibility(Activity activity,int id,int visible){

        return setVisibility(findById(activity,id),visible);
    }

    public static View setVisibility(View view,int id,int visible){

        return setVisibility(findById(view,id),visible);
    }

// </editor-fold>


//<editor-fold defaultState="collapsed" desc="Pxturn">

    public static int dpTopx(Context context,float dp){

        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,dp,context.getResources().getDisplayMetrics());
    }

// </editor-fold>


    //<editor-fold defaultState="collapsed" desc="Screen">

    public static int getScreenHeight(Context context){

        Activity activity = null;

        if(context instanceof Activity){

            activity = (Activity) context;
            WindowManager manager = activity.getWindowManager();
            DisplayMetrics outMetrics = new DisplayMetrics();
            manager.getDefaultDisplay().getMetrics(outMetrics);
            int width = outMetrics.widthPixels;
            int height = outMetrics.heightPixels;

            return  height;
        }

        return  0;
    }

    public static int getStateBarHeight(Context context){
        int result = 0;
        int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            result = context.getResources().getDimensionPixelSize(resourceId);

            return result;

        }else {

            return  -1;
        }
    }

    public static int getScreenWidth(Context context){

        Activity activity = null;

        if(context instanceof Activity){

            activity = (Activity) context;
            WindowManager manager = activity.getWindowManager();
            DisplayMetrics outMetrics = new DisplayMetrics();
            manager.getDefaultDisplay().getMetrics(outMetrics);
            int width = outMetrics.widthPixels;
            int height = outMetrics.heightPixels;

            return  width;
        }

        return  0;
    }


    public static boolean checkDeviceHasNavigationBar(Context activity) {

        //通过判断设备是否有返回键、菜单键(不是虚拟键,是手机屏幕外的按键)来确定是否有navigation bar
        boolean hasMenuKey = ViewConfiguration.get(activity)
                .hasPermanentMenuKey();
        boolean hasBackKey = KeyCharacterMap
                .deviceHasKey(KeyEvent.KEYCODE_BACK);

        if (!hasMenuKey && !hasBackKey) {
            // 做任何你需要做的,这个设备有一个导航栏
            return true;
        }
        return false;
    }

    public static int getNavigationBarHeight(Context activity) {
        Resources resources = activity.getResources();
        int resourceId = resources.getIdentifier("navigation_bar_height",
                "dimen", "android");
        //获取NavigationBar的高度
        int height = resources.getDimensionPixelSize(resourceId);
        return height;
    }


    // </editor-fold>

    //<editor-fold defaultState="collapsed" desc="TextVIew">


    public static TextView createEmptyTextView(String text,Context context){


        return  createTextView(text,context,-1,-1);
    }

    public static TextView createEmptyTextView(Context context){


        return  createEmptyTextView("数据为空",context);
    }

    public static TextView createTextView(String text,Context context){


        return createTextView(text,context,-2,-2);

    }

    public static TextView createTextView(String text,Context context,int width,int height){



        return  createTextView(text,context,width,height, Gravity.CENTER);

    }

    public static TextView createTextView(String text,Context context,int width,int height,int gravity){



        return  createTextView(text,context,width,height, gravity,14);

    }

    public static TextView createTextView(String text,Context context,int width,int height,int gravity,int textSize){


        return  createTextView(text,context,width,height, gravity,textSize, Color.BLACK);

    }

    public static TextView createTextView(String text,Context context,int width,int height,int gravity,int textSize,int textColor){

        TextView textView = new TextView(context);

        textView.setText(text);

        textView.setLayoutParams(new ViewGroup.LayoutParams(width,height));

        textView.setGravity(gravity);

        textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP,textSize);

        textView.setTextColor(textColor);

        return  textView;

    }




    public static String getTextContent(TextView textView){

        return textView.getText().toString().trim();
    }


    /**
     *  根据内容确定是否展示textview
     * @param textView view
     * @param content 内容
     */
    public static TextView setTextContent(TextView textView, String content){

        ZStringHelp.isEmpty(content,()-> textView.setVisibility(View.INVISIBLE), it->{
            textView.setVisibility(View.VISIBLE);
            textView.setText(it);
        });
        return  textView;
    }


    public static TextView setTextContent(TextView textView, String content, String defaultStr){

        textView.setVisibility(View.VISIBLE);
        textView.setText(ZStringHelp.initWithDefault(content,defaultStr));

        return  textView;
    }

    public static TextView setTextContent(Activity activity,int id,String content,String defaultStr){

        return   setTextContent(findById(activity,id),content,defaultStr);
    }

    public static TextView setTextContent(Activity activity,int id,String content){

        return    setTextContent(findById(activity,id),content);
    }


    public static TextView setTextContent(View view,int id,String content){

        return setTextContent(findById(view,id),content);
    }

    public static TextView setTextContent(View view,int id,String content,String defaultStr){

        return setTextContent(findById(view,id),content);
    }


// </editor-fold>

//<editor-fold defaultState="collapsed" desc="ImageView">

    public static void setImageRes(ImageView imageView,@DrawableRes int res){

        if(res == 0){

            imageView.setVisibility(View.GONE);
        }else {
            imageView.setVisibility(View.VISIBLE);
            imageView.setImageResource(res);
        }
    }

// </editor-fold>


//<editor-fold defaultState="collapsed" desc="keyboard">

    public static  void hideKeyBoard(Window window,Context context){

        InputMethodManager inputMethodManager = (InputMethodManager)context. getSystemService(Context.INPUT_METHOD_SERVICE);

        if (window.getCurrentFocus() != null)
            inputMethodManager.hideSoftInputFromWindow(window.getCurrentFocus().getWindowToken(),  0);
    }

    public static  void openKeyBoard(View v){

        InputMethodManager imm = ( InputMethodManager ) v.getContext().getSystemService( Context.INPUT_METHOD_SERVICE );
        if(!v.requestFocus()){
            v.requestFocus();
        }
        imm.showSoftInput(v,0);
    }

    public static void isShowSoftKeyBoard(EditText et,boolean isShow) {
        Class<EditText> cls = EditText.class;
        Method method;
        try {
            //setShowSoftInputOnFocus方法是EditText从TextView继承来的的
            //可以用来设置当EditText获得焦点时软键盘是否可见
            method = cls.getMethod("setShowSoftInputOnFocus", boolean.class);
            method.setAccessible(true);
            method.invoke(et, isShow);
        } catch (Exception e) {

        }

    }


    public static void disableShowSoftKeyBoard(EditText et) {
        isShowSoftKeyBoard(et,false);

    }
    public static void showSoftKeyBoard(EditText et) {
        isShowSoftKeyBoard(et,true);

    }

// </editor-fold>


    //<editor-fold defaultState="collapsed" desc="SpanString">

    public static SpannableString getRelativeSizeSpanString(String string,String str,float proportion){

        SpannableString spannableString = new SpannableString(string);

        if(!string.contains(str)){

            return  spannableString;
        }

        RelativeSizeSpan relativeSizeSpan = new RelativeSizeSpan(proportion);

        spannableString.setSpan(relativeSizeSpan,string.lastIndexOf(str),string.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);


        return  spannableString;

    }


    // </editor-fold>


    //<editor-fold defaultState="collapsed" desc="Toast">


    public static Toast createToast(Context context){


        return  Toast.makeText(context,null,Toast.LENGTH_SHORT);
    }




    public static Toast createToast(Context context,String string){


        return  Toast.makeText(context,string,Toast.LENGTH_SHORT);
    }



    public static Toast createToast(Context context,int time){


        return  Toast.makeText(context,null,time);
    }

    public static Toast createToast(Context context,String text,int time){


        return  Toast.makeText(context,text,time);
    }

    // </editor-fold>

    //<editor-fold defaultState="collapsed" desc="EditView">
    public static <T extends EditText> T addTextChangedListener(View view , @IdRes int id, TextWatcher watcher){

        T t =  findById(view,id);

        t.addTextChangedListener(watcher);

        return t;
    }

    public static <T extends EditText> T addTextChangedListener(Activity activity ,@IdRes int id, TextWatcher watcher){

        T t =  findById(activity,id);

        t.addTextChangedListener(watcher);

        return t;
    }
// </editor-fold>

//<editor-fold defaultState="collapsed" desc="widnow">

    public static void setStatusColor(Window window,int color,boolean  isLightBar,boolean showNavigation){

        if(color == Color.WHITE){


            isLightBar = true;
        }


        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {


            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
            window.getDecorView().setSystemUiVisibility(0);

            if(color == Color.TRANSPARENT)
            {

                if(isLightBar) {

                    window.getDecorView().setSystemUiVisibility(
                            View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
                }else {

                    window.getDecorView().setSystemUiVisibility(
                            View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE );

                }

            }else {

                if (isLightBar) {

                    window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);

                }
            }

            if(!showNavigation){

                window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION);


            }


            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);

            window.setStatusBarColor(color);

        }else {


        }

    }


    public static void setStatusBarTransparent(Window window,boolean isLightBar,boolean showNavigation){

        setStatusColor(window,Color.TRANSPARENT,isLightBar,showNavigation);

    }
    /**
     * 设置透明状态栏
     */
    public static void setStatusBarTransparent(Window window,boolean isLightBar){

        setStatusColor(window,Color.TRANSPARENT,isLightBar,true);

    }


    public static void printDisplayMetrics(Context context){

        DisplayMetrics dm = new DisplayMetrics();
        dm = context.getResources().getDisplayMetrics();
        float density  = dm.density;        // 屏幕密度（像素比例：0.75/1.0/1.5/2.0）  
        int densityDPI = dm.densityDpi;     // 屏幕密度（每寸像素：120/160/240/320）  
        float xdpi = dm.xdpi;
        float ydpi = dm.ydpi;


    }
// </editor-fold>
}
